<?php
include '../includes/cPlayer.php';
include '../includes/cDatabase.php';
include '../includes/cPage.php';
include '../includes/cDates.php';

$cPage = new page("Select Cup Weeks");
echo $cPage->getTitle();
echo $cPage->pageStringStart();
echo $cPage->contentStringStart();

if(@$_GET['form'] == "yes")
{
	$cDatabase = new database();

	$connect = $cDatabase->connectToDatabase();
	$activeDatabase = $cDatabase->getActiveDatabase($connect);
		
	$db = $cDatabase->selectDatabase($connect, $activeDatabase);

	$selectArray[0] = '*';
	$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, NULL, NULL, NULL, NULL);
	
	$round = 0;
	while ($weeksArray[$round] != NULL)
	{
		$cDatabase->insertTandbergCupWeeks($connect, ($round+1), $weeksArray[$round]);
		$round++;
	}
}
else
{
	$cDatabase = new database();

	$connect = $cDatabase->connectToDatabase();
	$activeDatabase = $cDatabase->getActiveDatabase($connect);
		
	$db = $cDatabase->selectDatabase($connect, $activeDatabase);

	$selectArray[0] = '*';
	$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, NULL, NULL, NULL, NULL);

	$numMembers = mysqli_num_rows($result);
	$numberRounds = CalculateNumberRounds($numMembers);
	
	//echo "rounds ".$numberRounds;

	$result = $cDatabase->DoesTableExist($connect, 'tandbergCup');
	if ($result == FALSE)
	{
		// Create this table
		echo"<BR>Tandberg Cup Table does not currently exist";
	}
	else
	{
		// Create form with a 'week' entry for each round
		$weeksArray = $_POST['weeksArray'];
		
		?>
	  	<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=yes" method="POST">
		<?php
		
	  	echo "<table border='0'>";
		for ($i = 1; $i <= $numberRounds; $i++)
		{ 
			echo "<tr>";
			echo "<td>Round ".$i."</td>";
			echo "<td><INPUT TYPE='text' NAME='weeksArray[]' VALUE='$week[$i]' size='3' maxlength='3'>";
			echo "</td></tr>";
		}
		echo "</table><div align='center'><table>";
		echo "<td colspan='2' align='center'>";
		echo "<input name='addWeeksButton' type='submit' id='addWeeks' value='Add'>";
		echo "</table></div></form>";
	}
}


function CalculateNumberRounds($numMembers)
{
	if ($numMembers > 64)
		return 7;
	else if ($numMembers > 32)
		return 6;
	else if ($numMembers > 16)
		return 5;
	else if ($numMembers > 8)
		return 4;
	else if ($numMembers > 4)
		return 3;
	else if ($numMembers > 2)
		return 2;
	else
		return 1;
}
echo $cPage->getContentStringEnd();
echo $cPage->getMenu();
echo $cPage->getClear();
echo $cPage->pageStringEnd();
echo $cPage->getFooter();
?>